#! /usr/bin/env node
const path = require('path')
const fs = require('fs')
const { program } = require('commander')
const packageConfig = require('../package.json')
const sourceMap = require('source-map')

const readFile = (filePath) => new Promise((resolve, reject) => {
  fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => {
    if (err) reject(err)
    else resolve(data.toString())
  })
})

program.version(packageConfig.version)  // --version 版本
  .requiredOption('-s, --source-path <sourcePath>', 'source-map文件地址')
  .requiredOption('-l, --line <line>', '设置错误所在行')
  .requiredOption('-c, --column <col>', '设置错误所在列')
  .description('source-map 工具')
  .action(async (options) => {

    const sourcePath = path.resolve(process.cwd(), options.sourcePath)
    const line = Number(options.line)
    const column = Number(options.column)

    const sourceMapFileContent = await readFile(sourcePath)
    const sourceMapContent = JSON.parse(sourceMapFileContent)
    const consumer = await new sourceMap.SourceMapConsumer(sourceMapContent);

    const originalPosition = consumer.originalPositionFor({
      line,
      column
    })

    consumer.destroy()
    console.log(originalPosition)

  })

program.parse(process.argv)
